package org.jeecg.modules.rental.util;

import org.jeecg.modules.rental.vo.LocationPoint;
import org.jeecg.modules.rental.vo.Polygon;
import org.jeecg.modules.rental.vo.Circle;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FenceMapperUtils {


    public static Polygon createPolygonFromCoordinates(String coordinates) {
        // 1. 去除首尾的括号（如果有）
        String trimmedCoordinates = coordinates.trim();
        if (trimmedCoordinates.startsWith("(") && trimmedCoordinates.endsWith(")")) {
            trimmedCoordinates = trimmedCoordinates.substring(1, trimmedCoordinates.length() - 1).trim();
        }

        // 2. 按照分号分割顶点
        String[] verticesStr = trimmedCoordinates.split(";");

        // 3. 将每个顶点转换为 LocationPoint 对象
        List<LocationPoint> vertices = Arrays.stream(verticesStr)
                .map(vertexStr -> {
                    // 3.1 去除顶点字符串中的空格
                    String trimmedVertexStr = vertexStr.trim();
                    // 3.2 去除顶点字符串中的括号（如果有）
                    if(trimmedVertexStr.startsWith("(") && trimmedVertexStr.endsWith(")")) {
                        trimmedVertexStr = trimmedVertexStr.substring(1,trimmedVertexStr.length() -1).trim();
                    }
                    // 3.3 按照逗号分割经纬度
                    String[] latLon = trimmedVertexStr.split(",");
                    if (latLon.length != 2) {
                        throw new IllegalArgumentException("Invalid polygon coordinates format: " + coordinates);
                    }
                    // 3.4 解析经纬度, 需要去除经纬度字符串中的空格和括号

                    double latitude = Double.parseDouble(latLon[0].trim().replace("(","").replace(")",""));
                    double longitude = Double.parseDouble(latLon[1].trim().replace("(","").replace(")",""));
                    return new LocationPoint(latitude, longitude);
                }).collect(Collectors.toList());

        return new Polygon(vertices);
    }


    public static Circle createCircleFromCoordinates(String coordinates) {
        // 1. 去除首尾的括号（如果有）
        String trimmedCoordinates = coordinates.trim();
        if (trimmedCoordinates.startsWith("(") && trimmedCoordinates.endsWith(")")) {
            trimmedCoordinates = trimmedCoordinates.substring(1, trimmedCoordinates.length() - 1).trim();
        }
        // 2. 按照逗号分割
        String[] parts = trimmedCoordinates.split(",");
        if (parts.length != 3) {
            throw new IllegalArgumentException("Invalid circle coordinates format: " + coordinates);
        }
        // 3. 解析参数
        double latitude = Double.parseDouble(parts[0].trim().replace("(","").replace(")",""));
        double longitude = Double.parseDouble(parts[1].trim().replace("(","").replace(")",""));
        double radius = Double.parseDouble(parts[2].trim().replace("(","").replace(")",""));

        LocationPoint center = new LocationPoint(latitude, longitude);
        return new Circle(center, radius);
    }
}
